<template>
  <div class="app-container">
    <el-row>
      <el-col :span="6">
        <el-card>
          <div slot="header" class="clearfix">
            <span style="font-weight:bold;color:#1890FF;font-size:14px;">数据目录</span>
          </div>
          <el-tree
            :data="treeData"
            :props="defaultProps"
            node-key="uuid"
            ref="tree"
            :default-expand-all="false"
            @node-click="handleNodeClick"
          >
          <span slot-scope="{ data }" class="custom-tree-node">
            <!--可以根据情况，以数据类型来显示不同的图标或图片-->
            <i v-if="data.level=='parent'" class="el-icon-folder-opened" style="color:blue;" />
            <i v-if="data.level=='root'" class="el-icon-folder-add" style="color:blue;" />
            <i v-if="data.level =='sub'" class="el-icon-tickets" style="color:blue;" />
            <span style="margin-left:5px;cursor:hand;">{{ data.name }}</span>
          </span>
          </el-tree>
        </el-card>
      </el-col>
      <el-col :span="18">
        <el-card>
          <div slot="header" class="clearfix">
            <span style="font-weight:bold;color:#1890FF;font-size:14px;">目录数据</span>
          </div>
          <div v-if="selectObject!=null">
            <el-button v-if="selectObject.level!='root'" type="success" plain @click="uploadData"><i class="el-icon-upload2"></i> &nbsp;&nbsp;数据上传</el-button>
             <el-table v-if="selectObject.level!='root'" :data="tableData" border style="margin-top:10px;">
              <el-table-column :label="'目录 ( '+selectObject.name+' ) 数据对象'" align="center">
                <el-table-column label="序号" align="center" type="index" width="55" />
                <el-table-column label="数据名称" align="center" prop="name">
                  <template slot-scope="scope">
                    <span v-if="scope.row.isDir==true" class="link-type" style="cursor:pointer;" @click="openFolder(scope.row.name)">{{ scope.row.name }}</span>
                    <span v-if="scope.row.isDir==false">{{ scope.row.name }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="完整名称" align="center" prop="fullname">
                  <template slot-scope="scope">
                    <span v-if="scope.row.isDir==true" class="link-type" style="cursor:pointer;" @click="openFolder(scope.row.name)">{{ scope.row.fullname }}</span>
                    <span v-if="scope.row.isDir==false">{{ scope.row.fullname}}</span>
                  </template>
                </el-table-column>
                <el-table-column label="文件大小" align="center" prop="size">
                  <template slot-scope="scope">
                    <span v-if="scope.row.isDir==true"></span>
                    <span v-if="scope.row.isDir==false">{{ scope.row.size }}</span>
                    <!-- <span v-if="scope.row.isDir==true&&scope.row.name.split('/').length>=3" @click="openPreFolder(preFolder)" style="color:blue;text-decoration:underline;margin-left:10px;cursor:pointer;">返回上一级</span> -->
                  </template>
                </el-table-column>
                <el-table-column label="操作" align="center" width="200">
                  <template slot-scope="scope">
                    <el-button size="mini" type="text" v-if="!(scope.row.fullname.indexOf('.xml')>=0)" :disabled="!(scope.row.fullname.indexOf('.shp')>=0||scope.row.fullname.indexOf('.glb')>=0||scope.row.fullname.indexOf('.gltf')>=0||scope.row.fullname.indexOf('.json')>=0)" icon="el-icon-view" @click="viewData(scope.row)">浏览</el-button>
                    <el-button size="mini" type="text" v-if="(scope.row.fullname.indexOf('.xml')>=0)" :disabled="(scope.row.fullname.indexOf('.xml')>=0)" @click="viewData(scope.row)">浏览</el-button>
                    <el-button size="mini" type="text" :disabled="!scope.row.isDir==false" icon="el-icon-download" @click="downloadFile(scope.row.url)">下载</el-button>
                    <el-button size="mini" type="text" style="color:red;" icon="el-icon-delete" @click="deleteBucketObject(scope.row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table-column>
            </el-table>
            <span v-if="selectObject.level=='root'" style="color:blue;font-size:14px;font-weight:bold;">此层级下无任何数据！</span>
          </div>
          <div v-if="selectObject==null">
            <span style="color:blue;font-size:14px;font-weight:bold;">请选择左侧，目录查看数据！</span>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-dialog :title="uTitle" :visible.sync="uOpen" width="70%" append-to-body>
      <el-card style="margin-top:-30px">
        <div slot="header" class="clearfix">
          <span style="font-weight:bold;font-size:18px;color:#329dff;">目录信息</span>
        </div>
        <el-descriptions v-if="selectObject!=null" :column="2" border>
          <el-descriptions-item label="名录名称" :labelStyle="{width:'10%','text-align': 'center'}" :contentStyle="{ width:'40%',color: '#329dff' }">
            {{ selectObject.name }}
          </el-descriptions-item>
          <el-descriptions-item v-if="selectObject.code!=undefined&&selectObject.code!=null" label="目录编码" :labelStyle="{width:'10%','text-align': 'center'}" :contentStyle="{ width:'40%',color: '#329dff' }">
            {{ selectObject.code }}
          </el-descriptions-item>
        </el-descriptions>
      </el-card>
      
      <el-card style="margin-top:10px">
        <div slot="header" class="clearfix">
          <span style="font-weight:bold;font-size:18px;color:#329dff;">目录数据对象上传</span>
        </div>
        <el-upload
          ref="upload"
          class="upload-files"
          :action="fileUrl"
          name="files"
          multiple
          :auto-upload="false"
          :file-list="fileList"
          :show-file-list="false"
          :before-upload="beforeAvatarUpload"
          :on-change="handleChange"
        >
          <el-button slot="trigger" type="primary">上传文件</el-button>
        </el-upload>

        <el-table v-if="fileList.length>0" :data="fileList" border style="margin-top:10px;">
          <el-table-column label="待传数据对象" align="center">
            <el-table-column label="序号" align="center" type="index" width="55" />
            <el-table-column label="数据对象名称" prop="name" />
          </el-table-column>
        </el-table>
      </el-card>

      <div slot="footer" class="dialog-footer" v-if="fileList.length>0">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="cancelUpload">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCatagory, getCatagory, delCatagory, addCatagory, updateCatagory } from "@/api/system/catagory";
import { getTreeRootData,getBucketObjects,deleteBucketObject,getBucketFolderObjects } from "@/api/system/catagory";
export default {
  name: "Catagory",
  data() {
    return {
      preFolder: null,
      fileList: [],
      selectObject: null,
      tableData: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 数据目录信息表表格数据
      catagoryList: [],
      treeData: [],
      defaultProps: {
        children: "children",
        label: "name"
      },
      // 弹出层标题
      uTitle: "",
      // 是否显示弹出层
      uOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        code: null,
        parentId: null,
        dataType: null,
        status: null,
        datasetIds: null,
        deptId: null,
        deptName: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      fileUrl: "",
    };
  },
  created() {
    // this.getList();
    this.getTreeRootData();
  },
  methods: {
    viewData(row){
      if(row.fullname.indexOf(".shp")>=0){
        this.$router.push({
          path: "/shpview",
          query: {
            url: row.url,
            fullname: row.fullname,
          }
        });
      }else if(row.fullname.indexOf(".glb")>=0||row.fullname.indexOf(".gltf")>=0){
        this.$router.push({
          path: "/bimview",
          query: {
            url: row.url
          }
        });
      }else if(row.fullname.indexOf(".json")>=0){
        this.$router.push({
          path: "/tileview",
          query: {
            url: row.url
          }
        });
      }
    },
    openPreFolder(folder){
      if(folder.split("/").length==2){
        let data = {
          uuid: this.selectObject.uuid
        }
        getBucketObjects(data).then(res =>{
          this.tableData = res.data;
        })
      }else{
        let pathArr = folder.split("/");
        let folderPath = "";
        for(let i=0;i<pathArr.length-2;i++){
          folderPath = folderPath+pathArr[i]+"/";
        }
        let data = {
          uuid: this.selectObject.uuid,
          folder: folderPath
        }
        getBucketFolderObjects(data).then(res =>{
          this.tableData = res.data;
        })
      }
    },
    openFolder(folder){
      this.preFolder = folder;
      let data = {
        uuid: this.selectObject.uuid,
        folder: folder
      }
      getBucketFolderObjects(data).then(res =>{
        this.tableData = res.data;
      })
    },
    downloadFile(url) {
      const fileUrl = url; // 文件的URL地址
      window.open(fileUrl);
    },
     beforeAvatarUpload(file) {
      // 手动修改fileList的值，需要在befoupload中添加
      if (!this.fileList) {
        this.fileList = [];
      }
      this.fileList.push(file);
    },
    cancelUpload(){
      this.uOpen = false;
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit()
      // this.fileList = [];
      this.uOpen = false;
      this.$modal.msgSuccess("上传成功，同步数据需要一点时间，上传结果视上传对象大小而定！");

      setTimeout(() => {
        if(this.preFolder==null){
          let data = {
            uuid: this.selectObject.uuid
          }
          getBucketObjects(data).then(res =>{
            this.tableData = res.data;
          })
        }else{
          let data = {
            uuid: this.selectObject.uuid,
            folder: this.preFolder
          }
          getBucketFolderObjects(data).then(res =>{
            this.tableData = res.data;
          })
        }
        
      }, 5000);
    },
    handleChange(file){
      this.fileList.push(file);
    },
    uploadData(){
      if(this.selectObject!=null){
        if(this.selectObject.level!="root"){
          this.fileList = [];
          this.uTitle = "数据上传";
          this.uOpen = true;
          this.fileUrl = process.env.VUE_APP_BASE_API + "/system/dataset/uploadDataFiles?bucket="+this.selectObject.uuid+"&folder="+this.preFolder;
        }
      }else{
        this.$message.error("请点击要查看的目录");
      }
    },
    handleNodeClick(object){
      this.preFolder = null;
      this.selectObject = object;
      if(object.level!="root"){
        let data = {
          uuid:object.uuid
        }
        getBucketObjects(data).then(res =>{
          this.tableData = res.data;
        })
      }
    },
    deleteBucketObject(row){
      let data = {
        oname: row.fullname,
        bname: this.selectObject.uuid
      }
      deleteBucketObject(data).then(res =>{
        this.$modal.msgSuccess("删除操作提交成功，删除数据需要一点时间，删除结果视删除对象大小而定！");
        setTimeout(() => {
          let data = {
            uuid: this.selectObject.uuid
          }
          getBucketObjects(data).then(res =>{
            this.tableData = res.data;
          })
        }, 5000);
      });
    },
    getTreeRootData(){
      getTreeRootData().then(res =>{
        this.treeData = res.data;
      })
    },
    /** 查询数据目录信息表列表 */
    getList() {
      this.loading = true;
      listCatagory(this.queryParams).then(response => {
        this.catagoryList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        uuid: null,
        name: null,
        code: null,
        parentId: null,
        dataType: null,
        status: null,
        datasetIds: null,
        deptId: null,
        deptName: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.uuid)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加数据目录信息表";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const uuid = row.uuid || this.ids
      getCatagory(uuid).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改数据目录信息表";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.uuid != null) {
            updateCatagory(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCatagory(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const uuids = row.uuid || this.ids;
      this.$modal.confirm('是否确认删除数据目录信息表编号为"' + uuids + '"的数据项？').then(function() {
        return delCatagory(uuids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/catagory/export', {
        ...this.queryParams
      }, `catagory_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
